﻿using System;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Networking.Proximity;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Navigation;
using NdefLibrary.Ndef;

namespace NFCTrigger
{
    public sealed partial class MainPage
    {
        #region Properties

        private CoreDispatcher MainDispatcher { get; set; }
        private ProximityDevice NfcDevice { get; set; }
        private Int64 CurrentMessageId { get; set; }

        #endregion

        #region Main methods

        public MainPage()
        {
            InitializeComponent();

            NavigationCacheMode = NavigationCacheMode.Required;
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            MainDispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
            NfcDevice = ProximityDevice.GetDefault();

            // Proximity device not found or disabled.
            if (NfcDevice == null)
            {
                PanelNoNfc.Visibility = Visibility.Visible;
                GridForm.Visibility = Visibility.Collapsed;
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // TODO: Prepare page for display here.

            // TODO: If your application contains multiple pages, ensure that you are
            // handling the hardware Back button by registering for the
            // Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
            // If you are using the NavigationHelper provided by some templates,
            // this event is handled for you.
        }

        #endregion

        #region Writing tags

        private void ButWrite_Click(Object sender, RoutedEventArgs e)
        {
            TxtUrl.IsEnabled = false;
            TxtMessage.IsEnabled = false;
            ButWrite.Visibility = Visibility.Collapsed;
            ButWriteCancel.Visibility = Visibility.Visible;
            LabelWriting.Visibility = Visibility.Visible;
            
            var appString = "{187e55e4-60ac-4a86-8c94-6b6e2bb2784f}";
            var arguments = TxtUrl.Text + "||" + TxtMessage.Text;
            var appRecord = new NdefLaunchAppRecord();
            appRecord.AddPlatformAppId("WindowsPhone", appString);
            appRecord.Arguments = arguments;

            var msg = new NdefMessage { appRecord };
            CurrentMessageId = NfcDevice.PublishBinaryMessage("NDEF:WriteTag", msg.ToByteArray().AsBuffer(), MesssageWritten);
        }

        private void ButWriteCancel_Click(Object sender, RoutedEventArgs e)
        {
            EnableForm();
        }

        private void MesssageWritten(ProximityDevice sender, long messageId)
        {
            MainDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                EnableForm();

                var msgBox = new MessageDialog("URL written to the NFC tag!");
                msgBox.ShowAsync();
            });
        }

        private void EnableForm()
        {
            if (CurrentMessageId > 0)
            {
                NfcDevice.StopPublishingMessage(CurrentMessageId);
            }

            TxtUrl.IsEnabled = true;
            TxtMessage.IsEnabled = true;
            LabelWriting.Visibility = Visibility.Collapsed;
            ButWriteCancel.Visibility = Visibility.Collapsed;
            ButWrite.Visibility = Visibility.Visible;
        }

        #endregion

        #region Reading tags

        private void BarRead_Click(object sender, RoutedEventArgs e)
        {

        }

        #endregion

        #region Help section

        private void BarHelp_Click(object sender, RoutedEventArgs e)
        {

        }

        #endregion
    }
}
